﻿using System;
using System.Text;
using System.Text.RegularExpressions;
using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Exceptions;
using Aliyun.Acs.Core.Profile;
using Aliyun.Acs.Dysmsapi.Model.V20170525;

namespace NetCoreCMS.Common
{
    //https://help.aliyun.com/document_detail/66265.html?spm=a2c4g.11186623.6.580.DlstE2
    public class AliSMS
    {
        static String product = "Dysmsapi";//短信API产品名称
        static String domain = "dysmsapi.aliyuncs.com";//短信API产品域名
        protected static string accessId = "LTAIEHDmBEil7Rh";
        protected static string accessSecret = "WTt11qacmm2Hbj5JsNyvUv6O4Spq3";
        protected static String regionIdForPop = "cn-hangzhou";
        protected static string signName = "会员系统";
        public AliSMS(string AccessId, string AccessSecret, string SignName)
        {
            accessId = AccessId;
            accessSecret = AccessSecret;
            signName = SignName;
        }
        /// <summary>
        /// 发短信
        /// </summary>
        /// <param name="mobiles">手机号码，以英文“,”逗号分隔开</param>
        /// <param name="TemplateCode">"SMS_103030015";管理控制台中配置的审核通过的短信模板的模板CODE（状态必须是验证通过）"</param>
        /// <param name="TemplateParam">"{\"code\":\"123\"}";短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。</param>
        /// <returns></returns>
        public bool Send(string mobiles, string TemplateCode, string TemplateParam)
        {
            string msg = "";
            //检查手机号码，如果超过2000则分批发送
            int sucCount = 0; //成功提交数量
            string errorMsg = string.Empty; //错误消息
            string[] oldMobileArr = mobiles.Split(',');

            StringBuilder sb = new StringBuilder();
            int sendCount = 0; //发送数量


            //检测号码，忽略不合格的，重新组合
            for (int j = 0; j < oldMobileArr.Length; j++)
            {
                string pattern = @"^1\d{10}$";
                string mobile = oldMobileArr[j].Trim();
                Regex r = new Regex(pattern, RegexOptions.IgnoreCase); //正则表达式实例，不区分大小写
                Match m = r.Match(mobile); //搜索匹配项
                if (m != null)
                {
                    sendCount++;
                    sb.Append(mobile + ",");
                }
            }

            //发送短信
            if (sb.Length > 11)
            {
                IClientProfile profile = DefaultProfile.GetProfile(regionIdForPop, accessId, accessSecret);
                DefaultProfile.AddEndpoint(regionIdForPop, regionIdForPop, product, domain);
                IAcsClient acsClient = new DefaultAcsClient(profile);
                SendSmsRequest request = new SendSmsRequest();
                try
                {
                    //request.SignName = "上云预发测试";//"管理控制台中配置的短信签名（状态必须是验证通过）"
                    //request.TemplateCode = "SMS_71130001";//管理控制台中配置的审核通过的短信模板的模板CODE（状态必须是验证通过）"
                    //request.RecNum = "13567939485";//"接收号码，多个号码可以逗号分隔"
                    //request.ParamString = "{\"name\":\"123\"}";//短信模板中的变量；数字需要转换为字符串；个人用户每个变量长度必须小于15个字符。"
                    //SingleSendSmsResponse httpResponse = client.GetAcsResponse(request);
                    request.PhoneNumbers = Utils.DelLastComma(sb.ToString());
                    request.SignName = signName;
                    request.TemplateCode = TemplateCode;
                    request.TemplateParam = TemplateParam.Replace("\\","");// "{\"code\":\"123\"}";
                    request.OutId = "xxxxxxxx";
                    //请求失败这里会抛ClientException异常
                    SendSmsResponse sendSmsResponse = acsClient.GetAcsResponse(request);
                    //System.Console.WriteLine(sendSmsResponse.Message);
                    sucCount += sendCount; //成功数量

                }
                catch (ServerException e)
                {
                    errorMsg = "提交失败，ServerException：" + e.Message;
                }
                catch (ClientException e)
                {
                    errorMsg = "提交失败，ClientException：" + e.Message;
                }
            }


            //返回状态
            if (sucCount > 0)
            {
                msg = mobiles;//"成功提交" + sucCount + "条，失败" + (oldMobileArr.Length - sucCount) + "条";
                return true;
            }
            msg = errorMsg;
            return false;
        }
    }
}
